package com.igeek.dao;

import com.igeek.domain.User;
import com.igeek.utils.JDBCTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author jerryHe
 * @create 2019-10-08 16:47
 */
public class UserDao {
    QueryRunner qr = new QueryRunner(JDBCTools.getDataSource());
    String sql ="";

    public boolean checkUsername(String username) {
        sql = "select * from user where username = ?";
        User u = null;
        try {
            u=qr.query(sql,new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u!=null?true:false;
    }

    public boolean login(User user) {
        sql ="select * from user where username = ? and password = ? and state = 1";
        User u = null;
        try {
            u = qr.query(sql,new BeanHandler<>(User.class),user.getUsername(),user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u!=null?true:false;
    }

    public void regist(User user) {
        String sql = "insert into user values (?,?,?,?,?,?,?,?,?,?)";
        try {
            qr.update(sql,user.getUid(),user.getUsername(),user.getPassword(),
                    user.getName(),user.getEmail(),user.getTelephone(),
                    user.getBirthday(),user.getSex(),user.getState(),
                    user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean checkActiveCode(String activeCode) {
        sql = "select * from user where code = ?";
        User user = null;
        try {
            user = qr.query(sql,new BeanHandler<>(User.class),activeCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user!=null?true:false;
    }


    public void updateActiveCode(String activeCode) {
        sql ="update user set state = 1 where code = ?";
        try {
            qr.update(sql,activeCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
